<?php

namespace App\Http\Controllers;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Http\Requests\OrderRequest;
use App\Jobs\CloseOrder;
use App\Models\CartItem;
use App\Models\Order;
use App\Models\ProductSku;
use App\Models\UserAddress;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrdersController extends Controller
{
    public function index(Request $request){
        $orders=Order::where(['user_id' => $request->user()->id])
            ->with('items.product', 'items.productSku')
            ->orderBy('created_at', 'desc')
            ->paginate();
        return view('orders.index', ['orders'=>$orders]);
    }
    public function show(Order $order){
        try{
            $this->authorize('own', $order);
        }catch (AuthorizationException $e){
            throw new InvalidRequestException('权限不够');
        }
        return view('orders.show',  ['order'=>$order->load('items.product', 'items.productSku')]);
    }
    public function store(OrderRequest $request){
        $order=DB::transaction(function() use($request){
            $user=$request->user();
            $address=UserAddress::find($request->input('address_id'));
            $order=new Order([
                'total_amount'=>0,
                'remark'=>$request->input('remark'),
                'address'=>[
                    'address'=>$address->getFullAddressAttribute(),
                    'zip'=>$address->zip,
                    'contact_name'=>$address->contact_name,
                    'contact_phone'=>$address->contact_phone,
                ]
            ]);
            $order->user()->associate($user);
            $order->save();

            $totalAmount=0;
            $items=$request->input('items');
            foreach($items as $item){
                $sku=ProductSku::find($item['sku_id']);
                $order->items()->make([
                    'product_id'=>$sku->product->id,
                    'product_sku_id'=>$sku->id,
                    'price'=>$sku->price,
                    'amount'=>$item['amount'],
                ])->save();
                $totalAmount+=$sku->price* $item['amount'];

                if(!$sku->decreaseStock($item['amount']))
                    throw new InvalidRequestException('商品库存不足');
            }
            $order->update(['total_amount'=>$totalAmount]);

            $skus=collect($items)->pluck('sku_id');
            $user->cartItems()->whereIn('product_sku_id', $skus)->delete();

            return $order;

        });
        CloseOrder::dispatch($order, config('app.order_ttl'));         //使用静态函数的写法
//            $this->dispatch(new CloseOrder($order, config('app.order_ttl'))); //使用 new 的写法
        return $order;
    }
}
